#include <iostream>
#include <fstream>
#include <sstream>

#include <cstdlib>
#include <unistd.h>
#include <pthread.h>

using namespace std;
int    threadNum;
string filename;

void * readThread(void * arg);
void * diskThread(void * arg);

int main(int argc, char ** argv)
{
    if (argc != 3) {
        cout << "Usage : " << argv[0]
             << " threadNum disknum" << endl;
        return -1;
    }

    threadNum = atoi(argv[1]);
    filename = "disktest";

    pthread_t tid;
    int disknum = atoi(argv[2]);
    for(int i=0; i < disknum; i++) {
    //for(int i=disknum-1; i >= 0; i--) {
        int * arg = new int(i);
        /*
        if (i == 1) 
            continue;
        if (i == 4 || i == 5) 
            continue;
        if (i == 2 || i == 3) 
            continue;
            */
        pthread_create(&tid, NULL, diskThread, (void *)arg);
    }

    for(;;) 
        sleep(1);

    return 0;
}

struct argS {
    int diskSeq;
    int seq;
};

void * diskThread(void * arg)
{
    int diskseq = *( (int *) arg);

    pthread_t tid;
    for(int i=0; i < threadNum; i++) {
        struct argS * arg = new argS;
        arg->diskSeq = diskseq;
        arg->seq = i;
        cout << " created thread disk [" << diskseq 
             << "] seq [" << i << "] " << endl;
        pthread_create(&tid, NULL, readThread, (void *)arg);
    }

    delete (int *)arg;
}

void * readThread(void * arg)
{
    struct argS & args = *( (struct argS *) arg);
    int disknum = args.diskSeq;
    int filenum = args.seq;
    size_t filelength, count;

    stringstream ss;
    ss << "/disk" << disknum << "/" << filename << filenum;

    ifstream diskfile; 

    char buf[40960];
    while(true) {
        diskfile.open(ss.str().c_str());
        if ( !diskfile.is_open() ) {
            cout << "Cannot open file : " << ss.str() << endl;
            return (void *)-1;
        }

        diskfile.seekg(0, ios::end);
        filelength = diskfile.tellg();
        diskfile.seekg(0, ios::beg);

        count = filelength;
        while(count > 0) {
            if (count >= 40960) {
                diskfile.read(buf, 40960);
                count -= 40960;
            } else {
                diskfile.read(buf, count);
                count = 0;
            }
            if (!diskfile.good() ) {
                cout << "file is not good " << ss.str() << endl;
            }
        }
        diskfile.close();
        cout << ss.str() << " done " << endl;
    }

    delete (struct argS *)arg;
}
